package com.atguigu.cloud.mygateway;


import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;


/**
 * ClassName:MyRoutePredicateFactory
 * Package:com.atguigu.cloud.mygateway
 * Description:
 *
 * @Author:@郭先森
 * @Create:2025/6/21 - 15:26
 * @Version:v1.0
 */
@Component
public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory<MyRoutePredicateFactory.Config>
{

    public MyRoutePredicateFactory(){
        super(MyRoutePredicateFactory.Config.class);
    }
    //这个Config就是我们的路由断言规则，重要
    @Validated
    public static class Config{
        @Setter@Getter@NotEmpty
        private String userType;
    }
    @Override
    public Predicate<ServerWebExchange> apply(MyRoutePredicateFactory.Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                //http://192.168.1.72:9527/pay/gateway/get/1?userType=diamond

                //获得request从参数的里边，判断userType的值是否为指定的值，如果是就就放行
                String userType = serverWebExchange.getRequest().getQueryParams().getFirst("userType");
                if(userType==null){
                    return false;
                }
                if(userType.equalsIgnoreCase(config.getUserType())){
                    //如果说参数存在就和config的数据进行比较
                    return true;
                }
                return false;
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userType");
    }
}



